package com.atguigu.yygh.hosp.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.yygh.common.handler.YyghException;
import com.atguigu.yygh.hosp.repository.DepartmentRepository;
import com.atguigu.yygh.hosp.service.DepartmentService;
import com.atguigu.yygh.model.hosp.Department;
import com.atguigu.yygh.vo.hosp.DepartmentQueryVo;
import com.atguigu.yygh.vo.hosp.DepartmentVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 科室
 */
@Service
public class DepartmentServiceImpl implements DepartmentService {

    @Autowired
    private DepartmentRepository departmentRepository;

    /**
     * 上传科室信息
     *
     * @param paramMap
     */
    @Override
    public void saveDepartment(Map<String, Object> paramMap) {
        //1.转化参数类型
        String jsonString = JSONObject.toJSONString(paramMap);
        Department department = JSONObject.parseObject(jsonString, Department.class);
        //2.根据hoscode、depcode查询科室信息
        Department targetDepartment =
                departmentRepository.getByHoscodeAndDepcode(//跟据两个参数进行筛选一条唯一数据
                        department.getHoscode(),
                        department.getDepcode()
                );
        if (targetDepartment != null) { //不为空时
            //3.有，更新
            department.setId(targetDepartment.getId());
            department.setCreateTime(targetDepartment.getCreateTime());
            department.setUpdateTime(new Date());                           //最后一次更新时间
            department.setIsDeleted(targetDepartment.getIsDeleted());       //调用targetDepartment原值
            departmentRepository.save(department);  //保存
        } else {
            //4.没有，新增
            department.setCreateTime(new Date());
            department.setUpdateTime(new Date());
            department.setIsDeleted(0);         // 默认0，未删除
            departmentRepository.save(department);
        }
    }

    /**
     * 分页查询实现 （带条件带分页查询科室信息数据）
     *
     * @param page              当前页码
     * @param limit             每页记录数
     * @param departmentQueryVo 查询条件
     * @return
     */
    @Override
    public Page<Department> selectPage(int page, int limit, DepartmentQueryVo departmentQueryVo) {
        //1、创建分页查询对象
        //  1.1创建排序对象
        Sort sort = Sort.by(Sort.Direction.DESC, "createTime");
        //  1.2创建分页对象
        Pageable pageable = PageRequest.of((page - 1), limit, sort);

        //2、创建条件查询模板
        //  2.1封装查询条件到实体对象
        Department department = new Department();
        BeanUtils.copyProperties(departmentQueryVo, department);//把departmentQueryVo中的几个值赋给department
        //  2.2创建模板构造器   （创建匹配器，即如何使用查询条件）
        ExampleMatcher matcher = ExampleMatcher.matching() //构建对象
                .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING)//改变默认字符串匹配方式：模糊查询
                .withIgnoreCase(true); //改变默认大小写忽略方式：忽略大小写
        //  2.3创建模板
        Example<Department> example = Example.of(department, matcher);

        //3、带条件带分页查询
        Page<Department> pageModel = departmentRepository.findAll(example, pageable);

        return pageModel;
    }

    /**
     * 删除科室数据（跟据主键id）
     *
     * @param hoscode
     * @param depcode
     */
    @Override
    public void remove(String hoscode, String depcode) {  // hoscode主键id， depcode科室编号
        //1.先查询，根据hoscode、depcode查询科室信息
        Department department =
                departmentRepository.getByHoscodeAndDepcode(//跟据两个参数，筛选一条唯一数据
                        hoscode,  // 科室id
                        depcode   //  科室编号
                );
        //2.跟据id删除
        if (department != null) {
//            departmentRepository.deleteById(department.getId());
            department.setIsDeleted(1); //伪删除
            department.setUpdateTime(new Date());//修改该条数据的修改时间
            departmentRepository.save(department);
        }
    }

    /**
     * 根据医院编号，查询医院所有科室列表
     *
     * @param hoscode 医院编号
     *                2023年3月3日 09点47分
     */
    @Override
    public List<DepartmentVo> getDeptTreeList(String hoscode) {
        //1、创建最终返回数据对象List<DepartmentVo>，用于最终数据封装
        List<DepartmentVo> result = new ArrayList<>();
        //2、跟据医院编码查询所有科室信息List<DepartmentVo>，查询医院所有科室信息
        //  departmentList 所有科室列表
        List<Department> departmentList = departmentRepository.getByHoscode(hoscode);
        //3、借助工具，数据类型转化
        //   List<DepartmentVo> => Map<bigcode,List<Department>>
        //   根据大科室编号  bigcode 分组，获取每个大科室里面下级子科室
        Map<String, List<Department>> departmentMap =
                departmentList.stream().collect(
                        Collectors.groupingBy(Department::getBigcode)
                );
        //4、遍历map集合 deparmentMap 封装大科室数据
        for (Map.Entry<String, List<Department>> entry : departmentMap.entrySet()) {
            DepartmentVo bigDepVo = new DepartmentVo();
            bigDepVo.setDepcode(entry.getKey());//大科室编号
            bigDepVo.setDepname(entry.getValue().get(0).getBigname());//大科室名字 （此时已经拿到科室value，类型不同需要继续转换↓）
            //5、封装小科室信息  List<DepartmentVo>
            List<DepartmentVo> departmentVoList = new ArrayList<>();
            List<Department> depList = entry.getValue();
            for (Department department : depList) {
                DepartmentVo depVo = new DepartmentVo();
                depVo.setDepcode(department.getDepcode());
                depVo.setDepname(department.getDepname());
                //封装到list集合
                departmentVoList.add(depVo);
            }
            //6、封装小科室集合存入大科室   把小科室list集合放到大科室departmentVoList里面
            bigDepVo.setChildren(departmentVoList);
            //7、大科室对象存入最终返回对象
            result.add(bigDepVo);
        }
        return result;
    }

    /**
     * 查询（单个）科室
     * @param hoscode
     * @param depcode
     * @return
     */
    @Override
    public Department getDepartment(String hoscode, String depcode) {
        //查询，根据hoscode、depcode查询科室信息
        Department department =
                departmentRepository.getByHoscodeAndDepcode(//跟据两个参数，筛选一条唯一数据
                        hoscode,  // 科室id
                        depcode   //  科室编号
                );
        return department;
    }

    /**
     * 查询科室名称
     * @param hoscode 医院编号
     * @param depcode 科室编码
     * @return
     */
    @Override
    public String getDepName(String hoscode, String depcode) {
        //查询，根据hoscode、depcode查询科室信息
        Department department =
                departmentRepository.getByHoscodeAndDepcode(//跟据两个参数，筛选一条唯一数据
                        hoscode,  // 科室id
                        depcode   //  科室编号
                );
        if (department == null) {
            throw new YyghException(20001,"科室信息不存在！");
        }
        return department.getDepname();
    }


}